package com.weicong.library;

import android.content.Context;
import android.support.annotation.DrawableRes;
import android.support.v4.view.PagerAdapter;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;

import com.bumptech.glide.Glide;

import java.util.ArrayList;

public class ImageUrlAdapter extends PagerAdapter {

    /**
     * 图片视图缓存列表
     */
    private ArrayList<ImageView> mImageViewCacheList;

    /**
     * 图片资源id列表
     */
    private ArrayList<String> mImageUrls;

    /**
     * 占位图片的资源id
     */
    private int mPlaceholderRes;

    /**
     * item单击监听器
     */
    private ImageCycleView.OnItemClickListener mListener;

    /**
     * 上下文
     */
    private Context mContext;

    public ImageUrlAdapter(Context context, ArrayList<String> imageUrls,
                           @DrawableRes int placeholderRes,
                           ImageCycleView.OnItemClickListener listener) {
        mContext = context;
        mImageUrls = imageUrls;
        mPlaceholderRes = placeholderRes;
        mImageViewCacheList = new ArrayList<>();
        mListener = listener;
    }

    @Override
    public int getCount() {
        return mImageUrls.size();
    }

    @Override
    public boolean isViewFromObject(View view, Object obj) {
        return view == obj;
    }

    @Override
    public Object instantiateItem(ViewGroup container, final int position) {
        ImageView imageView;
        if (mImageViewCacheList.isEmpty()) {
            imageView = new ImageView(mContext);
            imageView.setScaleType(ImageView.ScaleType.CENTER_CROP);
        } else {
            imageView = mImageViewCacheList.remove(0);
        }
        Glide.with(mContext)
                .load(mImageUrls.get(position))
                .placeholder(mPlaceholderRes)
                .crossFade()
                .into(imageView);
        imageView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (mListener != null) {
                    mListener.onItemClick(v, position);
                }
            }
        });
        container.addView(imageView);
        return imageView;
    }

    @Override
    public void destroyItem(ViewGroup container, int position, Object object) {
        ImageView view = (ImageView) object;
        container.removeView(view);
        mImageViewCacheList.add(view);
    }
}
